package com.ethink.platform.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.mdm.api.MateFacade;
import com.ethink.mdm.api.info.MateSkuInfo;
import com.ethink.order.api.GroupMateFacade;
import com.ethink.order.api.constant.OrderConstant;
import com.ethink.order.api.info.GroupMateDetailInfo;
import com.ethink.order.api.model.TobSaleSettleExcelModel;
import com.ethink.order.api.response.GroupMateDetailResponse;
import com.ethink.platform.common.properties.PlatformCommonProperties;
import com.ethink.platform.controller.order.info.TobSaleSettleImportInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author default
 * @version 1.0.0
 * @ClassName TobSaleSettleManager.java
 * @Description
 * @createTime 2022年11月18日 13:45:00
 */
@Component
@Slf4j
public class TobSaleSettleManager {

    @Autowired
    private ExcelImportManager excelImportManager;

    @Autowired
    private PlatformCommonProperties platformCommonProperties;

    @Autowired
    private MateFacade mateFacade;

    @Autowired
    private GroupMateFacade groupMateFacade;

    public List<TobSaleSettleImportInfo> importTobSaleSettleOrder(MultipartFile file, String saleSubChannel) {
        List<TobSaleSettleExcelModel> tobSaleSettleModels = excelImportManager.transferClass(file, TobSaleSettleExcelModel.class);
        // 根据渠道，查询所有的组套商品
        List<String> groupMateSkuList = groupMateFacade.getGroupMateSkuList(saleSubChannel);
        if (CollectionUtils.isNotEmpty(groupMateSkuList)) {
            List<TobSaleSettleExcelModel> newModels = new ArrayList<>();
            Iterator<TobSaleSettleExcelModel> iterator = tobSaleSettleModels.iterator();
            Map<String, GroupMateDetailResponse> cache = new HashMap<>();
            while (iterator.hasNext()) {
                TobSaleSettleExcelModel model = iterator.next();
                String groupMateSku = model.getMateSku();
                if (groupMateSkuList.contains(groupMateSku)) {
                    iterator.remove();
                    GroupMateDetailResponse groupMate = cache.get(groupMateSku);
                    if (groupMate == null) {
                        groupMate = groupMateFacade.getGroupMateByGroupMateSku(saleSubChannel, model.getMateSku());
                        cache.put(groupMateSku, groupMate);
                    }
                    BigDecimal totalPrice = model.getSettlePrice();
                    BigDecimal itemSumPrice = groupMate.getItems().stream().map(GroupMateDetailInfo::getSalePrice)
                            .reduce(new BigDecimal(0), (m, n) -> m.add(n));
                    // 一个商品要拆成多个
                    for (int i = 0; i < groupMate.getItems().size(); i++) {
                        GroupMateDetailInfo item = groupMate.getItems().get(i);
                        TobSaleSettleExcelModel newModel = new TobSaleSettleExcelModel();
                        newModel.setPoOrderNo(model.getPoOrderNo());
                        newModel.setMateSku(item.getMateSku());
                        newModel.setMateSkuName(item.getMateSkuName());
                        newModel.setSettleQty(item.getQty() * model.getSettleQty());
                        BigDecimal salePrice = totalPrice.multiply(item.getSalePrice()).divide(itemSumPrice, 6, RoundingMode.HALF_UP);
                        newModel.setSettlePrice(salePrice);
                        newModels.add(newModel);
                    }
                }
            }
            tobSaleSettleModels.addAll(newModels);
        }
        //唯品特殊校验po单号
        if (OrderConstant.Z102.equals(saleSubChannel)) {
            List<TobSaleSettleExcelModel> checkList = tobSaleSettleModels.stream().filter(a -> StrUtil.isBlank(a.getPoOrderNo()) || StrUtil.isBlank(a.getMateSku()))
                    .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(checkList)) {
                throw new BusinessException(CommonRespCode.PARAM_ERR, "po单号,商品编码不能为空");
            }
        } else {
            List<TobSaleSettleExcelModel> checkList = tobSaleSettleModels.stream().filter(a -> StrUtil.isBlank(a.getMateSku()))
                    .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(checkList)) {
                throw new BusinessException(CommonRespCode.PARAM_ERR, "商品编码不能为空");
            }
        }
        Set<String> mateSkuSet = new HashSet();
        for (TobSaleSettleExcelModel tobSaleSettleModel : tobSaleSettleModels) {
            mateSkuSet.add(tobSaleSettleModel.getMateSku());
        }
        List<String> mateSkuList = new ArrayList<>(mateSkuSet);
        List<MateSkuInfo> mateSkuInfos = mateFacade.queryMateSkuBySkuCodeList(mateSkuList);
        if (mateSkuList.size() != mateSkuInfos.size()) {
            throw new BusinessException(CommonRespCode.PARAM_ERR, "文件中含有不存在的商品编码");
        }
        Map<String, MateSkuInfo> skuMap = mateSkuInfos.stream().collect(Collectors.toMap(MateSkuInfo::getMateSku, Function.identity()));
        HashSet<String> poOrderNoList = platformCommonProperties.getPo();
        Integer count = 1;
        List<TobSaleSettleImportInfo> importInfoList = new ArrayList<>();
        for (TobSaleSettleExcelModel tobSaleSettleModel : tobSaleSettleModels) {
            TobSaleSettleImportInfo importInfo = BeanUtil.copyProperties(tobSaleSettleModel, TobSaleSettleImportInfo.class);
            importInfo.setKey(count);
            if (importInfo.getPoOrderNo() != null && poOrderNoList.contains(importInfo.getPoOrderNo())) {
                importInfo.setSourcePoOrderNo(importInfo.getPoOrderNo());
                importInfo.setPoOrderNo(platformCommonProperties.getJoinPo());
            }
            importInfo.setMateSkuName(skuMap.get(tobSaleSettleModel.getMateSku()).getMateSkuName());
            importInfoList.add(importInfo);
            count++;
        }
        return importInfoList;
    }
}
